<?php

namespace App\Library\Tencent\TencentCloud;

use Exception;
use Qcloud\Cos\Client;
use QCloud\COSSTS\Sts;

/**
 *
 */
class BaseTencentCloudApi
{
    private $secretId;
    private $secretKey;

    protected $domain;

    protected $bucket;
    protected $region;

    /**
     * @var Client
     */
    protected Client $client;

    const TEMP_KEYS_DURATION_SECONDS = 1800;

    const TEMP_KEYS = 'sts.tencentcloudapi.com';

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $this->secretId  = config('library.tencent_cloud.secretId');
        $this->secretKey = config('library.tencent_cloud.secretKey');
        $this->domain    = config('library.tencent_cloud.domain');
        $this->bucket    = config('library.tencent_cloud.bucket');
        $this->region    = config('library.tencent_cloud.region');
    }

    /**
     * @param $tempKeys
     * @return string
     */
    protected function getUrl($tempKeys): string
    {
        return 'https://' . $tempKeys;
    }

    /**
     *
     * @param string $pathPrefix
     * @return array
     * @throws Exception
     */
    protected function getTempKeys(string $pathPrefix): array
    {
        $sts    = new Sts();
        $config = [
            'url'             => $this->getUrl(self::TEMP_KEYS), // url和domain保持一致
            'domain'          => self::TEMP_KEYS, // 域名，非必须，默认为 sts.tencentcloudapi.com
            'secretId'        => $this->secretId, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'secretKey'       => $this->secretKey, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'bucket'          => $this->bucket, // 换成你的 bucket
            'region'          => $this->region, // 换成 bucket 所在园区
            'durationSeconds' => self::TEMP_KEYS_DURATION_SECONDS, // 密钥有效期
            'allowPrefix'     => [$pathPrefix . '/*'], // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions'    => [
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
            ],
        ];

        // 获取临时密钥，计算签名
        $accessTokenData = $sts->getTempKeys($config);

        return [
            'tmpSecretId'  => $accessTokenData['credentials']['tmpSecretId'],
            'tmpSecretKey' => $accessTokenData['credentials']['tmpSecretKey'],
            'accessToken'  => $accessTokenData['credentials']['sessionToken'],
            'expiredTime'  => $accessTokenData['expiredTime'],
        ];
    }

    /**
     * 获取链接
     */
    public function createClient()
    {
        $this->client = new Client([
            'region'      => $this->region,
            'scheme'      => 'https', //协议头部，默认为http
            'credentials' => [
                'secretId'  => $this->secretId,
                'secretKey' => $this->secretKey,
            ],
        ]);
    }
}
